﻿Imports EstoqueBLL
Imports ModuloFinanceiro

Class ComprasCAD
    Dim objbll As New ComprasBLL
    Dim objforn As New FornecedorBLL
    Dim objprod As New PECABLL
    Dim tabitens As New DataTable
    Dim frete As New Decimal
    Public Op As Char
#Region "Métodos"
#Region "Carrega na Datagirdview"
    Sub Carrega_Selecao(itens As ItensCompraBLL)
        Try
            Dim soma As Decimal = 0
            Dim linha As DataRow
            linha = tabitens.NewRow
            linha("pro_codigo") = itens.pro_codigo
            linha("pec_codbarra") = objprod.pec_codbarra
            linha("pro_descricao") = objprod.pro_descricao
            linha("itc_qtde") = itens.itc_qtde
            linha("itc_valorunitario") = itens.itc_valorunitario
            linha("itc_valortotal") = itens.itc_valortotal
            linha("itc_desconto") = itens.itc_desconto
            linha("itc_substtrib") = itens.itc_substtrib
            linha("itc_ipi") = itens.itc_ipi
            linha("itc_frete") = itens.itc_frete
            linha("itc_custoreal") = itens.itc_custoreal
            linha("itc_margcontrib") = itens.itc_margcontrib
            linha("itc_porcentagem") = itens.itc_porcentagem
            linha("itc_precovenda") = itens.itc_precovenda
            tabitens.Rows.Add(linha)
            tabitens.AcceptChanges()
            For Each x In tabitens.Rows
                soma += Decimal.Parse(x("itc_valortotal"))
            Next
            LVTotalFinal.Text = soma
        Catch ex As Exception
            Throw New Exception("Erro ao inserir na grid")
        End Try

    End Sub

#End Region

#Region "Edita na Datagridview"
    Public Sub editanagrid(itens As ItensCompraBLL, indice As Integer)
        tabitens.Rows(indice)("pro_codigo") = itens.pro_codigo
        tabitens.Rows(indice)("pec_codbarra") = objprod.pec_codbarra
        tabitens.Rows(indice)("pro_descricao") = objprod.pro_descricao
        tabitens.Rows(indice)("itc_qtde") = itens.itc_qtde
        tabitens.Rows(indice)("itc_valorunitario") = itens.itc_valorunitario
        tabitens.Rows(indice)("itc_valortotal") = itens.itc_valortotal
        tabitens.Rows(indice)("itc_desconto") = itens.itc_desconto
        tabitens.Rows(indice)("itc_substtrib") = itens.itc_substtrib
        tabitens.Rows(indice)("itc_ipi") = itens.itc_ipi
        tabitens.Rows(indice)("itc_frete") = itens.itc_frete
        tabitens.Rows(indice)("itc_custoreal") = itens.itc_custoreal
        tabitens.Rows(indice)("itc_margcontrib") = itens.itc_margcontrib
        tabitens.Rows(indice)("itc_porcentagem") = itens.itc_porcentagem
        tabitens.Rows(indice)("itc_precovenda") = itens.itc_precovenda
        tabitens.AcceptChanges()
        Dim soma As Decimal
        For Each x In tabitens.Rows
            soma += Decimal.Parse(x("itc_valortotal"))
        Next
        LVTotalFinal.Text = soma
    End Sub
#End Region

#Region "Valida Item"
    Function validaItem(codigoproduto As Integer) As Boolean
        Dim ret As Boolean
        ret = False
        For Each linha As DataRow In tabitens.Rows
            If (linha("pro_codigo") = codigoproduto) Then
                ret = True
            End If
        Next
        Return ret
    End Function

#End Region

#Region "Lista"
    Sub Lista()
        tabitens = New DataTable()
        Try
            tabitens.Columns.Add("pro_codigo", GetType(Integer))
            tabitens.Columns.Add("pec_codbarra", GetType(String))
            tabitens.Columns.Add("pro_descricao", GetType(String))
            tabitens.Columns.Add("itc_qtde", GetType(Integer))
            tabitens.Columns.Add("itc_valorunitario", GetType(Decimal))
            tabitens.Columns.Add("itc_valortotal", GetType(Decimal))
            tabitens.Columns.Add("itc_desconto", GetType(Decimal))
            tabitens.Columns.Add("itc_substtrib", GetType(Decimal))
            tabitens.Columns.Add("itc_ipi", GetType(Decimal))
            tabitens.Columns.Add("itc_frete", GetType(Decimal))
            tabitens.Columns.Add("itc_custoreal", GetType(Decimal))
            tabitens.Columns.Add("itc_margcontrib", GetType(Decimal))
            tabitens.Columns.Add("itc_porcentagem", GetType(Decimal))
            tabitens.Columns.Add("itc_precovenda", GetType(Decimal))
            DGVDados.DataSource = tabitens

        Catch
            Throw New Exception("Erro ao gerar lista")
        End Try

    End Sub
#End Region

#Region "Limpa"
    Sub limpa()
        tabitens = New DataTable
        TFornecedor.Clear()
        objforn = New FornecedorBLL
        TValorFrete.Text = "0,00"
        TVTnota.Text = "0,00"
    End Sub
#End Region

#Region "Carregar Campos"
    Sub carregarcampos()
        objbll = New ComprasBLL(Val(LCodigo.Text))
        tabitens = objbll.buscaritens()
        tabitens.AcceptChanges()
        DGVDados.DataSource = tabitens
        TNumeroNota.Text = objbll.com_numnota
        objforn = New FornecedorBLL(objbll.for_codigo)
        TFornecedor.Text = objforn.nomefantasia
        TValorFrete.Text = objbll.com_valorfrete
        TVTnota.Text = objbll.com_valortotal
        DTPChegada.Value = objbll.com_dtchegada
        DTPDataEmissao.Value = objbll.com_dtemissao
        If (objbll.com_valorfrete > 0) Then TValorFrete_LostFocus(Nothing, Nothing)
    End Sub
#End Region
#End Region

#Region "Eventos"
#Region "Load"
    Private Sub ComprasCAD_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        limpa()
        Lista()
        If (Op = "E") Then
            carregarcampos()
            Dim soma As Decimal = 0
            For Each linha As DataGridViewRow In Me.DGVDados.Rows
                If (Not linha.Cells("itc_valortotal") Is Nothing) Then
                    soma += Decimal.Parse(linha.Cells("itc_valortotal").Value)
                End If
            Next
            LVTotalFinal.Text = soma
        End If
    End Sub
#End Region

#Region "Botão add produto"
    Private Sub TSBAdiconar_Click(sender As System.Object, e As System.EventArgs) Handles TSBAdiconar.Click
        Try
            TValorFrete_LostFocus(Nothing, Nothing)
            Dim frm As New CompraProduto
            frm.TPorcFrete.Text = FormatPercent(frete / 100)
            frm.ShowDialog()
            If (Not IsNothing(frm.objitens)) Then
                If (frm.objitens.pro_codigo > 0) Then
                    Try
                        If (Not validaItem(frm.objitens.pro_codigo)) Then
                            objprod = frm.objpeca
                            Carrega_Selecao(frm.objitens)
                        Else : Throw New Exception("Produto já inserido.")
                        End If

                    Catch ex As Exception
                        MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Finally
                    End Try
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

    End Sub
#End Region

#Region "Botão busca fornecedor"
    Private Sub BBuscaFornecedor_Click(sender As System.Object, e As System.EventArgs) Handles BBuscaFornecedor.Click
        Dim frm As New FornecedorCON
        frm.tipo = "ret"
        frm.ShowDialog()
        If (Not IsNothing(frm.objforn)) Then
            objforn = frm.objforn
            TFornecedor.Text = objforn.nomefantasia
        End If
    End Sub
#End Region

#Region "Voltar"
    Private Sub TSBVoltar_Click(sender As System.Object, e As System.EventArgs) Handles TSBVoltar.Click
        Me.Close()
    End Sub
#End Region

#Region "Keypress"
    Private Sub TValorFrete_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TNumeroNota.KeyPress
        If Not (Char.IsNumber(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True
        If (TNumeroNota.Text.Contains(",") = False And e.KeyChar = ",") Then e.Handled = False

    End Sub
    Private Sub TValorFrete_KeyPress_1(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TValorFrete.KeyPress, TVTnota.KeyPress
        If Not (Char.IsNumber(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True
        Dim x As New TextBox
        x = sender '

        If (x.Text.Contains(",") = False And e.KeyChar = ",") Then e.Handled = False

    End Sub

    Private Sub ComprasCAD_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            SendKeys.Send("{TAB}")
        End If
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
#End Region

#Region "Remover da Datagridview"
    Private Sub BExcluir_Click(sender As System.Object, e As System.EventArgs) Handles TSBExcluir.Click
        Try
            Dim indice As Integer
            indice = -1

            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("pro_codigo") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                tabitens.Rows.RemoveAt(indice)
                tabitens.AcceptChanges()
            Else : Throw New Exception("Selecione um produto para remover")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

#End Region

#Region "Editar na DataGridView"
    Private Sub TSBEditar_Click(sender As System.Object, e As System.EventArgs) Handles TSBEditar.Click
        Try
            TValorFrete_LostFocus(Nothing, Nothing)
            Dim indice As Integer
            indice = -1

            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("pro_codigo") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                Dim frm As New CompraProduto
                frm.status = "E"
                frm.objitens = New ItensCompraBLL
                frm.objitens.itc_custoreal = tabitens.Rows(indice)("itc_custoreal")
                frm.objitens.itc_desconto = tabitens.Rows(indice)("itc_desconto")
                frm.objitens.itc_frete = frete
                frm.objitens.itc_ipi = tabitens.Rows(indice)("itc_ipi")
                frm.objitens.itc_margcontrib = tabitens.Rows(indice)("itc_margcontrib")
                frm.objitens.itc_porcentagem = tabitens.Rows(indice)("itc_porcentagem")
                frm.objitens.itc_precovenda = tabitens.Rows(indice)("itc_precovenda")
                frm.objitens.itc_qtde = tabitens.Rows(indice)("itc_qtde")
                frm.objitens.itc_substtrib = tabitens.Rows(indice)("itc_substtrib")
                frm.objitens.itc_valortotal = tabitens.Rows(indice)("itc_valortotal")
                frm.objitens.itc_valorunitario = tabitens.Rows(indice)("itc_valorunitario")
                frm.objitens.pro_codigo = tabitens.Rows(indice)("pro_codigo")
                frm.ShowDialog()
                If (frm.status = "O" And Not IsNothing(frm.objitens)) Then
                    objprod = frm.objpeca
                    editanagrid(frm.objitens, indice)
                End If
            Else : Throw New Exception("Selecione um produto para editar")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
        
    End Sub
#End Region

#Region "Salvar/Alterar"
    Private Sub TSBSalvar_Click(sender As System.Object, e As System.EventArgs) Handles TSBGravar.Click
        Try
            If (objforn.Codigo > 0) Then
                Dim vfrete, vtotal As Decimal
                vfrete = 0
                vtotal = 0
                Decimal.TryParse(TValorFrete.Text.Replace("R$", ""), vfrete)
                Decimal.TryParse(TVTnota.Text.Replace("R$", ""), vtotal)

                If (MessageBox.Show("Deseja finalizar a compra?", "Finalização", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes) Then
                    'se for fechar a compra
                    If (Math.Round(vtotal) = Math.Round(Decimal.Parse(LVTotalFinal.Text.Replace("R$", "")))) Then
                        'se bater o total com a nota
                        Dim obnj As New ComprasBLL(Val(LCodigo.Text))
                        If (obnj.com_codigo > 0) Then
                            objbll = New ComprasBLL(Val(LCodigo.Text), DTPChegada.Value, DTPDataEmissao.Value, obnj.com_dtpedido, TNumeroNota.Text, vfrete, vtotal, objforn.Codigo, 4)
                        Else
                            objbll = New ComprasBLL(Val(LCodigo.Text), DTPChegada.Value, DTPDataEmissao.Value, Now, TNumeroNota.Text, vfrete, vtotal, objforn.Codigo, 4)
                        End If
                        objbll.valida()
                        Dim obj As ItensCompraBLL
                        For Each linha As DataRow In tabitens.Rows
                            obj = New ItensCompraBLL
                            obj.itc_custoreal = linha("itc_custoreal")
                            obj.itc_desconto = linha("itc_desconto")
                            obj.itc_frete = linha("itc_frete")
                            obj.itc_ipi = linha("itc_ipi")
                            obj.itc_margcontrib = linha("itc_margcontrib")
                            obj.itc_porcentagem = linha("itc_porcentagem")
                            obj.itc_precovenda = linha("itc_precovenda")
                            obj.itc_qtde = linha("itc_qtde")
                            obj.itc_substtrib = linha("itc_substtrib")
                            obj.itc_valortotal = linha("itc_valortotal")
                            obj.itc_valorunitario = linha("itc_valorunitario")
                            obj.pro_codigo = linha("pro_codigo")
                            obj.validarcampos()
                            obj.validarfrete(vtotal, vfrete)
                            objbll.litens.Add(obj)
                        Next
                        objbll.inseriralterar(objusuarios.Codigo)
                        Dim objpagar = New ContasaPagarFRM
                        objpagar.ControlBox = False
                        objpagar.TSBFechar.Visible = False
                        objpagar.finaliza = ""
                        objpagar.objCompras = objbll
                        objpagar.ShowDialog()
                        If (objpagar.finaliza = "OK") Then
                            objbll.sta_codigo = 6
                        Else
                            Throw New Exception("Operação de lançamento no contas a pagar não foi concluido, a compra não foi finalizada")
                        End If

                    Else
                        Throw New Exception("O valor total não corresponde ao valor declarado da nota, por favor confira os itens")
                    End If
                Else
                    objbll = New ComprasBLL(Val(LCodigo.Text), DTPChegada.Value, DTPDataEmissao.Value, objbll.com_dtpedido, TNumeroNota.Text, vfrete, vtotal, objforn.Codigo, 4)
                    objbll.validadatas()
                    Dim obj As ItensCompraBLL
                    For Each linha As DataRow In tabitens.Rows
                        obj = New ItensCompraBLL
                        obj.itc_custoreal = linha("itc_custoreal")
                        obj.itc_desconto = linha("itc_desconto")
                        obj.itc_frete = linha("itc_frete")
                        obj.itc_ipi = linha("itc_ipi")
                        obj.itc_margcontrib = linha("itc_margcontrib")
                        obj.itc_porcentagem = linha("itc_porcentagem")
                        obj.itc_precovenda = linha("itc_precovenda")
                        obj.itc_qtde = linha("itc_qtde")
                        obj.itc_substtrib = linha("itc_substtrib")
                        obj.itc_valortotal = linha("itc_valortotal")
                        obj.itc_valorunitario = linha("itc_valorunitario")
                        obj.pro_codigo = linha("pro_codigo")
                        objbll.litens.Add(obj)
                    Next
                End If
                objbll.inseriralterar(objusuarios.Codigo)
                MessageBox.Show("Compra gravada com sucesso", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information)
                limpa()
                Me.Close()
            Else
                Throw New Exception("Defina um fornecedor")
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub
#End Region

#Region "LostFocus"
    Private Sub TValorFrete_LostFocus(sender As Object, e As System.EventArgs) Handles TValorFrete.LostFocus, TVTnota.LostFocus
        Dim res, res2 As Boolean
        Dim f, n, aux As New Decimal
        res = Decimal.TryParse(TValorFrete.Text.Replace("R$", ""), f)
        res2 = Decimal.TryParse(TVTnota.Text.Replace("R$", ""), n)
        aux = n
        If (res And res2) Then
            If n <> 0 Then
                frete = (f / n) * 100
            Else
                n = 1
                frete = (f / n) * 100
                n = aux
            End If

        Else
            frete = 0
        End If
        TValorFrete.Text = FormatCurrency(f)
        TVTnota.Text = FormatCurrency(n)
    End Sub
#End Region

#End Region


End Class